import { defineStore } from 'pinia'
import { ref, computed } from 'vue'


export const useUserStore = defineStore('user', () => {
  // 状态
  const access_token = ref(localStorage.getItem('access_token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  // 计算属性
  const isLoggedIn = computed(() => !!access_token.value)
  
  // 动作
  const setToken = (newToken) => {
    access_token.value = newToken
    localStorage.setItem('access_token', newToken)
  }
  
  const setUserInfo = (info) => {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  
  const login = (tokenData, userData) => {
    setToken(tokenData)
    setUserInfo(userData)
  }
  
  const logout = async () => {
    try {
      if (userId.value) {
        await logout(userId.value)
      }
    } catch (error) {
      console.error('退出登录API调用失败:', error)
    } finally {
      // 无论API调用是否成功，都清除本地数据
      clearAuth()
    }
  }
  
  const clearAuth = () => {
    access_token.value = ''
    userInfo.value = {}
    localStorage.removeItem('access_token')
    localStorage.removeItem('userInfo')
  }
  
  // 记住账号和密码功能（合并存储）
  const setRememberedCredentials = (account, password) => {
    const credentials = {
      account: account || '',
      password: password || ''
    }
    // 密码使用 Base64 编码存储（不是加密，仅是简单混淆）
    if (credentials.password) {
      credentials.password = btoa(credentials.password)
    }
    localStorage.setItem('remembered_credentials', JSON.stringify(credentials))
  }
  
  const getRememberedCredentials = () => {
    const stored = localStorage.getItem('remembered_credentials')
    if (!stored) return { account: '', password: '' }
    try {
      const credentials = JSON.parse(stored)
      // 解码密码
      if (credentials.password) {
        try {
          credentials.password = atob(credentials.password)
        } catch {
          credentials.password = ''
        }
      }
      return {
        account: credentials.account || '',
        password: credentials.password || ''
      }
    } catch {
      return { account: '', password: '' }
    }
  }
  
  const clearRememberedCredentials = () => {
    localStorage.removeItem('remembered_credentials')
  }
  
  // 备考类型映射
  const getPreparationTypeName = (type) => {
    const typeMap = {
      1: '小学',
      2: '初中',
      3: '高中',
      4: '四级',
      5: '六级',
      6: '专四',
      7: '专八',
      8: '考研',
      9: '雅思',
      10: '托福'
    }
    return typeMap[type] || '未知'
  }
  
  return {
    // 状态
    access_token,
    userInfo,
    // 计算属性
    isLoggedIn,
    // 动作
    setToken,
    setUserInfo,
    login,
    logout,
    clearAuth,
    getPreparationTypeName,
    setRememberedCredentials,
    getRememberedCredentials,
    clearRememberedCredentials
  }
})
